import { _decorator, Component, sys } from 'cc';
import { DEBUG, DEV, PREVIEW } from 'cc/env';

const { ccclass, property } = _decorator;

import { Consts } from "../Data/Consts";
import TAComponent from "../sdk/TAComponent";
import WebApiMgr from "./WebApiMgr";
const GAME_DATA_KEY = 'game_data'

@ccclass('UserDataMgr')
export default class UserDataMgr extends Component {
    static Instance: UserDataMgr;
    private _data: object;
    private _loginSucc = false;
    protected onLoad(): void {
        UserDataMgr.Instance = this;
    }
    protected start(): void {
        const storageStr = sys.localStorage.getItem(GAME_DATA_KEY)
        const localData = storageStr ? JSON.parse(storageStr) : {}
        this._data = localData
        if (!this._data['data_version']) {
            this._data['data_version'] = 0
        }
    }
    async readDataFromServer(): Promise<string> {
        try {
            // return await WebApiMgr.Instance.readData()
        } catch (error) {
            return this.readDataFromServer()
        }
    }
    async init(loginSucc: boolean = true): Promise<void> {
        this._loginSucc = loginSucc
        if (!loginSucc) {
            return
        }
        const jsonStr = await this.readDataFromServer()
        if (!jsonStr) {
            return
        }
        const serverData = JSON.parse(jsonStr)
        if (!serverData) {
            return
        }
        if (!serverData['data_version']) {      // 服务器有老数据
            this._data = serverData
            this._data['data_version'] = 1
            // WebApiMgr.Instance.saveData(JSON.stringify(this._data))
            // cc.sys.localStorage.setItem(GAME_DATA_KEY, JSON.stringify(this._data))
            // cc.director.emit(Message.DATA_REFRESH)
        } else if (serverData['data_version'] > this._data['data_version']) {
            this._data = serverData
            sys.localStorage.setItem(GAME_DATA_KEY, JSON.stringify(serverData))
            // cc.director.emit(Message.DATA_REFRESH)
        } else if (serverData['data_version'] < this._data['data_version']) {
            // WebApiMgr.Instance.saveData(JSON.stringify(this._data))
        }
        // this._loginSucc = loginSucc;
        // if (!loginSucc) return;
        // try {
        //     const jsonStr = await WebApiMgr.Instance.readData();
        //     this._data = jsonStr ? JSON.parse(jsonStr) : {};
        //     return await Promise.resolve();
        // } catch (err) {
        //     cc.error(err);
        //     return await this.init();
        // }
    }
    getItem(key: string) {
        if (this._data[key]) {
            return this._data[key]
        } else if (sys.localStorage.getItem(key)) {
            this._data[key] = sys.localStorage.getItem(key)
            return this._data[key]
        }
        // if (this._loginSucc)
        //     return this._data[key];
        // else
        //     return cc.sys.localStorage.getItem(key);
    }
    async setItem(key: string, value: string) {
        this._data[key] = value
        this.save()
    }
    save() {
        this._data['data_version']++
        const jsonStr = JSON.stringify(this._data)
        sys.localStorage.setItem(GAME_DATA_KEY, jsonStr)
        if (this._loginSucc) {
            // WebApiMgr.Instance.saveData(jsonStr)
        }
    }
    //    // 登录相关逻辑
    async DealLogin(accountId) {
        if (!PREVIEW && !DEBUG) {
            // this._loadConfig(accountId);
        }
        else {
            // 处理登录 探针
            let loginSucc = false;
            this.LoginPlatform(accountId, loginSucc);
        }
    }
    async LoginPlatform(accountId, loginSucc) {
        if (sys.platform == sys.Platform.BYTEDANCE_MINI_GAME) {
            loginSucc = await new Promise<boolean>(res => {
                this._ttLogin().then(() => res(true)).catch(() => res(false));
            });
            TAComponent.setSuperProperties({ channel: 'tt' });
            TAComponent.userSetOnce({ channel: 'tt' });
        }

        else if (typeof window['KSGameGlobal'] != 'undefined') {
            console.log("KSGameGlobal.login---------------");


            loginSucc = await new Promise<boolean>(res => {
                this._ksLogin().then(() => res(true)).catch(() => res(false));
            });
            TAComponent.setSuperProperties({ channel: 'ks' });
            TAComponent.userSetOnce({ channel: 'ks' });


        } else if (window['wx']) {
            loginSucc = await new Promise<boolean>(res => {
                this._wxLogin().then(() => res(true)).catch(() => res(false));
            });
            TAComponent.setSuperProperties({ channel: 'wx' });
            TAComponent.userSetOnce({ channel: 'wx' });
        }
        else if (PREVIEW || window['h5api']) {

        }
        else {
            console.log("TAComponent.getDeviceId()---------", TAComponent.getDeviceId());

            loginSucc = true;
            accountId = await WebApiMgr.login({ platform: 'web', mac_id: TAComponent.getDeviceId() });
            console.log("accountId:------------", accountId);

            TAComponent.login(accountId);
            TAComponent.setSuperProperties({ channel: 'web' });
            TAComponent.userSetOnce({ channel: 'web' });
        }

        console.log("accountId:------------", accountId);

        this.init(loginSucc);
    }
    async _wxLogin() {
        const loginRes = await new Promise<{ code: string }>((res, rej) => wx.login({
            success: res,
            fail: rej,
        }));
        // const accountId = await WebApiMgr.Instance.login({ platform: 'wx', code: loginRes.code });
        // TAComponent.api.login(accountId);
    }
    async _ttLogin() {
        console.log('_ttLogin-----------');

        const loginRes = await new Promise<{ errMsg: string, code: string, anonymousCode: string, isLogin: boolean }>((res, rej) => tt.login({
            success: res,
            fail: ({ errMsg }) => {
                console.error(errMsg);
                rej(errMsg);
            }
        }));
        console.log('WebApiMgr.login-----------');

        // const accountId = await WebApiMgr.login({ platform: 'tt', code: loginRes.code, anonymous_code: loginRes.anonymousCode });
        const accountId = await WebApiMgr.login({ platform: 'tt', code: loginRes.code, appid: Consts.appid.抖音 });
        TAComponent.login(accountId);
        console.log('TAComponent.login-----------');

        const { query, group_id } = tt.getLaunchOptionsSync();
        WebApiMgr.conversion('active', query, { 'group_id': group_id });
    }
    async _ksLogin() {
        console.log("_ksLogin()-----------------------", 1);

        const loginRes = await new Promise<{ code: string }>((res, rej) => ks.login({
            success: res,
            fail: rej,
        }));
        console.log("_ksLogin()-----------------------", 2);


        const accountId = await WebApiMgr.login({ platform: 'ks', code: loginRes.code, appid: Consts.appid.快手 });
        console.log("_ksLogin-----------accountId:------------", accountId);

        TAComponent.login(accountId);
        const { query } = ks.getLaunchOptionsSync();
        WebApiMgr.KSConversion('active', query);
    }

    //    // async _loadConfig(accountId) {
    //    //     let version = '0.0.1_正式';
    //    //     if (cc.sys.isBrowser && location.href.includes('after')) {
    //    //         version = '达人_底部';
    //    //     } else if (cc.sys.isBrowser && location.href.includes('before')) {
    //    //         version = '达人_腰部';
    //    //     } else if (cc.sys.isBrowser && location.href.includes('live')) {
    //    //         version = '直播';
    //    //     } else if (cc.sys.platform == cc.sys.BYTEDANCE_GAME) {
    //    //         version = tt.getLaunchOptionsSync().extra.mpVersion + '_抖音';
    //    //     } else if (typeof window['KSGameGlobal'] != 'undefined') {
    //    //         version = '1.2.22_快手';
    //    //     } else if (cc.sys.platform == cc.sys.WECHAT_GAME) {
    //    //         const accountInfo = wx.getAccountInfoSync();
    //    //         version = accountInfo.miniProgram.envVersion == 'release' ? accountInfo.miniProgram.version + '_微信' : 'test_微信';
    //    //     }
    //    //     let alltotallevel = levelConfig.totalLevel;
    //    //     const storageKey = 'config_cache';
    //    //     const readCache = () => {
    //    //         if (localStorage.getItem(storageKey)) {
    //    //             levelConfig.totalLevel = JSON.parse(localStorage.getItem(storageKey));
    //    //         } else {
    //    //             // 过滤掉前6关
    //    //             levelConfig.totalLevel = levelConfig.totalLevel.filter((v, i) => i > 5);
    //    //         }
    //    //     }
    //    //     readCache();
    //    //     this.BeginGetConfig(alltotallevel, storageKey, version);
    //    //     let loginSucc = false;
    //    //     this.LoginPlatform(accountId, loginSucc);
    //    // }
    //    // async BeginGetConfig(alltotallevel, storageKey, version) {
    //    //     let remoteConfig: (typeof levelConfig.totalLevel) = await this.getConfigFromServer(version)
    //    //     if (!remoteConfig)
    //    //         return;
    //    //     remoteConfig = remoteConfig.filter(lc => alltotallevel.findIndex(local => local.name == lc.name) > -1)
    //    //         .map((lc, idx) => {
    //    //             lc.bundle = alltotallevel.find(c => c.name == lc.name).bundle;
    //    //             return lc;
    //    //         });
    //    //     if (remoteConfig.length > 0) {
    //    //         levelConfig.totalLevel = remoteConfig;
    //    //         localStorage.setItem(storageKey, JSON.stringify(levelConfig.totalLevel));
    //    //     }
    //    //     cc.director.emit(Message.Refresh_PageView);
    //    // }
    //    // async getConfigFromServer(version): Promise<any> {
    //    //     try {
    //    //         return await WebApiMgr.Instance.getConfig(version)
    //    //     } catch (error) {
    //    //         return this.getConfigFromServer(version)
    //    //     }
    //    // }
}
